`
https://leetcode.cn/problems/length-of-longest-subarray-with-at-most-k-frequency/
`

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var maxSubarrayLength = function (nums, k) {
  const n = nums.length
  const freq = new Map()
  let res = 0
  let left = 0, right = 0

  while (right < n) {
    const n1 = nums[right++]
    freq.set(n1, (freq.get(n1) || 0) + 1)

    // 收缩窗口
    while (freq.get(n1) > k) {
      const n2 = nums[left++]
      if (freq.get(n2) === 1) freq.delete(n2)
      else freq.set(n2, freq.get(n2) - 1)
    }

    // 更新答案
    res = Math.max(res, right - left)
  }

  return res
};